<template>
  <a-card :bordered='false'>
    <!-- 查询区域 -->
    <search ref='search' :config='searchConfig' @search='search' @getHeight='getHeight' />
    <!-- 操作按钮区域 -->
    <div class='page_table'>
      <vxe-grid
        ref='xGrid'
        :border='true'
        :resizable='true'
        :showOverflow='true'
        size='mini'
        :loading='loading'
        :height='pageHeight-seachHeight-94'
        :align='left'
        :columns='columns'
        :data='dataSource'
        :toolbar-config="tableToolbar"
       :checkbox-config="checkboxConfig"
        v-bind='vexConfig'
        @checkbox-change='selectChangeEvent'
        @checkbox-all="selectChangeEvent"
      >
        <template #toolbar_buttons>
          <div class='table-operator'>
            <a-button v-has="'warehousecig:add'" @click='handleAdd'>新增</a-button>
            <a-button v-has="'warehousecig:delete'" @click='batchDel'>删除</a-button>
            <a-button v-has="'warehousecig:synchronization'" @click="downExportXls('cnProduct_service')">同步</a-button>
            <a-button v-has="'warehousecig:export'" @click="downExportXls('cnProduct_service' )">导出</a-button>
          </div>
        </template>

        <template #detail='{ row,rowIndex }'>
          <a style='color: #1890FF' @click='handleAdd(row,"详情",true,true)'>{{ row.warehouseCode }}</a>
        </template>

        <template #updateStatus='{ row }'>
          <a-switch :checked='row.status' size='small' @change='handleStatus(row,$event)' />
        </template>

        <template #action='{ row }'>
          <a v-has="'warehousecig:update'" @click='handleAdd(row,"编辑")'>编辑</a>
          <a-divider type='vertical' />
          <a v-has="'business:log'" href='javascript:' @click='handleBusiness("仓库配置",row)'>日志</a>
        </template>
        <template #pager>
          <vxe-pager
            :layouts="['Total', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump','Sizes', 'FullJump']"
            :currentPage.sync='ipagination.current'
            :page-size.sync='ipagination.pageSize'
            :total='ipagination.total'
            :pageSizes='ipagination.pageSizeOptions'
            @page-change='handlePageChange'>
          </vxe-pager>
        </template>
      </vxe-grid>
    </div>
    <!-- table区域-begin -->

    <form-add-edit ref='formAdd' @ok='modalFormOk'></form-add-edit>
    <business-log ref='businessLog'></business-log>
  </a-card>
</template>

<script>
  import { getProductCategory } from '@/api/api'
  import FormAddEdit from '@comp/view/base-crud/form/FormAddEdit'
  import JSuperQuery from '@/components/cn-form/JSuperQuery.vue'
  import JInput from '@/components/cn-form/JInput.vue'
  import { initDictOptions, filterDictText, filterDictTextByCache } from '@/components/dict/CnDictSelectUtil'
  import { PageListMixin } from '@/mixins/PageListMixin'
  import Vue from 'vue'
  import { filterObj } from '@/utils/util'
  import JTreeSelect from '@/components/cn-form/JTreeSelect'
  import { getAction } from '@/api/manage'
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import search from '@comp/view/base-crud/search/Search'

  export default {
    name: 'product-list',
    mixins: [PageListMixin],
    components: {
      FormAddEdit,
      JSuperQuery,
      JInput,
      JTreeSelect,
      search
    },
    data() {
      return {
        description: '仓库配置',
        selectedRowKeys: [],
        importExcelUrl: window._CONFIG['domianURL'] + '/cnProductController/importExcel',
        searchConfig: [
          {
            // label:'订单编号',
            type: 'input',
            name: 'warehouseCode',
            placeholder: '仓库编号'
          },
          {
            // label:'订单编号',
            type: 'input',
            name: 'warehouseName',
            placeholder: '仓库名称'
          },
          {
            // label:'订单编号',
            type: 'input',
            name: 'warehouseType',
            placeholder: '仓库类型'
          },
          {
            type: 'a-select',
            name: 'status',
            placeholder: '请选择状态',
            option: [
              {
                name: '启用',
                value: 1
              },
              {
                name: '停用',
                value: 0
              }]
          },
          {
            type: 'input',
            name: 'factoryName',
            placeholder: '工厂'
          },
          {
            type: 'input',
            name: 'warehousePattern',
            placeholder: '库存模式'
          }
        ],
        //表头
        columns: [],
        //列设置
        settingColumns: [],
        //列定义
        defColumns: [
          { type: 'checkbox', width: 60, fixed: 'left' },

          {
            title: '仓库编号',
            field: 'warehouseCode',
            width: 120,
            fixed: 'left',
            slots: {
              default: 'detail'
            }
          },
          {
            title: '仓库名称',
            align: 'left',
            width: 120,
            ellipsis: true,
            field: 'warehouseName',
            minWidth: 80,
          },
          {
            title: '工厂',
            align: 'left',
            ellipsis: true,
            field: 'factoryName',
            minWidth: 80,
          },
          {
            title: '仓库类型',
            align: 'left',
            ellipsis: true,
            field: 'warehouseType',
            minWidth: 80,
          },
          {
            title: '库存模式',
            align: 'left',
            width: 120,
            ellipsis: true,
            field: 'warehousePattern',
            minWidth: 80,
          },
          {
            title: '是否允许负库存',
            align: 'left',
            ellipsis: true,
            field: 'isNegativeInventory',
            minWidth: 120,
          },
          {
            title: '是否启用库存管理',
            align: 'left',
            width: 120,
            ellipsis: true,
            field: 'isStockManage',
            minWidth: 80,
          },
          {
            title: '备注',
            align: 'left',
            ellipsis: true,
            field: 'remarks',
            minWidth: 80,
          },
          {
            title: '创建人',
            align: 'left',
            ellipsis: true,
            field: 'createName',
            minWidth: 80,
          },
          {
            title: '创建时间',
            align: 'left',
            ellipsis: true,
            field: 'createTime',
            minWidth: 80,
          },
          {
            title: '更新人',
            align: 'left',
            ellipsis: true,
            field: 'updateName',
            minWidth: 80,
          },
          {
            title: '更新时间',
            align: 'left',
            ellipsis: true,
            field: 'updateTime',
            minWidth: 80,
          },
          {
            title: '状态',
            align: 'center',
            field: 'action',
            fixed: 'right',
            width: 120,
            slots: {
              default: 'updateStatus'
            }
          },
          {
            title: '操作',
            field: 'action',
            fixed: 'right',
            align: 'center',
            width: 150,
            slots: {
              default: 'action'
            }
          }
        ],
        url: {
          list: '/warehouseconfig/cnWarehouseConfig/findPageList',
          delete: '/warehouseconfig/cnWarehouseConfig/delete',
          detail: '/warehouseconfig/cnWarehouseConfig/saveOrUpdate',
          deleteBatch: '/warehouseconfig/cnWarehouseConfig/deleteBatch',
          exportXlsUrl: window._CONFIG['domianURL'] + '/cnProductController/exportXls',
          deleteTag: '/cnTerminalController/deleteLabels',
          saveOrUpdateTag: window._CONFIG['domianURL'] + '/cnTerminalController/saveOrUpdateLabels',
          startOrStopUrl: window._CONFIG['domianURL'] + '/warehouseconfig/cnWarehouseConfig/startOrStop',
          // 导入接口
          importExcelUrl: window._CONFIG['domianURL'] + '/cnProductController/importExcel'
        }
      }
    },
    created() {
      this.initColumns()
    },
    methods: {
      startorstop: function(status) {
        if (!this.url.startOrStopUrl) {
          this.$message.error('请设置url启用停用!')
          return
        }
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！')

        } else {
          var ids = ''
          for (var a = 0; a < this.selectedRowKeys.length; a++) {
            ids += this.selectedRowKeys[a] + ','
          }
          var that = this
          this.$confirm({
            title: '确认修改',
            content: '是否修改选中数据?',
            onOk: function() {
              that.loading = true
              getAction(that.url.startOrStopUrl, { ids: ids, status: status }).then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.loadData()
                  that.onClearSelected()
                } else {
                  that.$message.warning(res.message)
                }
              }).finally(() => {
                that.loading = false
              })
            }
          })
        }
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectionRows = selectionRows
      },
      onClearSelected() {
        this.selectedRowKeys = []
        this.selectionRows = []
      },
      getQueryParams() {
        //高级查询器
        let sqp = {}
        if (this.superQueryParams) {
          sqp['superQueryParams'] = encodeURI(this.superQueryParams)
          sqp['superQueryMatchType'] = this.superQueryMatchType
        }
        var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)

        param.field = this.getQueryField()
        param.current = this.ipagination.current
        param.size = this.ipagination.pageSize
        delete param.birthdayRange //范围参数不传递后台
        return filterObj(param)
      },


      //列设置更改事件
      onColSettingsChange(checkedValues) {
        var key = this.$route.name + ':colsettings'
        Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
        this.settingColumns = checkedValues
        const cols = this.defColumns.filter(item => {
          if (item.key == 'rowIndex' || item.field == 'action') {
            return true
          }
          if (this.settingColumns.includes(item.field)) {
            return true
          }
          return false
        })
        this.columns = cols
      },
      changeStatus(e, item) {

        if (e) {
          this.startorstopByid(1, item.id)
        } else {
          this.startorstopByid(0, item.id)
        }
      },
      startorstopByid(status, id) {
        let that = this
        this.$confirm({
          title: '确认修改',
          content: '是否' + (status == 0 ? '停用' : '启动') + '选中数据？',
          onOk() {
            that.loading = true
            getAction(that.url.startOrStopUrl, { ids: id, status: status }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.loading = false
            })
          },
          onCancel() {
            // that.loadData();
            // that.onClearSelected();
          }
        })
      },
      initColumns() {
        //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
        //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

        var key = this.$route.name + ':colsettings'
        let colSettings = Vue.ls.get(key)
        if (colSettings == null || colSettings == undefined) {
          let allSettingColumns = []
          this.defColumns.forEach(function(item, i, array) {
            allSettingColumns.push(item.field)
          })
          this.settingColumns = allSettingColumns
          this.columns = this.defColumns
        } else {
          this.settingColumns = colSettings
          const cols = this.defColumns.filter(item => {
            if (item.key == 'rowIndex' || item.field == 'action') {
              return true
            }
            if (colSettings.includes(item.field)) {
              return true
            }
            return false
          })
          this.columns = cols
        }
      },

      async handleAdd(record = {}, title = '新增', disabled = false, disableSubmit = false) {
        if (record.id && this.url.detail) {
          const res = await getAction(this.url.detail, { id: record.id })
          if (res.success) {
            if (res.result) {
              record = res.result
            }
          }
        }
        let config = {
          title: title,
          width: 800,
          addOrUpdateUrl: `${window._CONFIG['domianURL']}/warehouseconfig/cnWarehouseConfig/saveOrUpdate`,  //审核地址
          method: 'post',
          labelCol: {
            xs: { span: 24 },
            sm: { span: 7 }
          },
          wrapperCol: {
            xs: { span: 24 },
            sm: { span: 15 }
          },
          list: [
            {
              label: '仓库编号',
              type: 'input',
              placeholder: '仓库编号',
              md: 12,
              disabled: disabled,
              name: 'warehouseCode',  // 后台接受字段
              check: { rules: [{ required: true, message: '经销商编号' }] }
            },
            {
              label: '仓库名称',
              type: 'input',
              md: 12,
              disabled: disabled,
              placeholder: '仓库名称',
              name: 'warehouseName'  // 后台接受字段
            },
            {
              label: '仓库类型',
              type: 'input',
              md: 12,
              disabled: disabled,
              placeholder: '仓库类型',
              name: 'warehouseType'  // 后台接受字段
            },
            {
              label: '库存模式',
              type: 'input',
              md: 12,
              disabled: disabled,
              placeholder: '库存模式',
              name: 'warehousePattern'  // 后台接受字段
            },
            {
              label: '允许负库存',
              md: 12,
              disabled: disabled,
              // type: 'date-range', //范围选择
              // range:['startDate','endDate'],
              type: 'a-select',
              placeholder: '是否允许负库存',
              name: 'isNegativeInventory',  // 后台接受字段
              option: [
                {
                  name: '是',
                  value: '是'
                },
                {
                  name: '否',
                  value: '否'
                }
              ]
            },
            {
              label: '启动库存管理',
              md: 12,
              disabled: disabled,
              // type: 'date-range', //范围选择
              // range:['startDate','endDate'],
              type: 'a-select',
              placeholder: '是否启动库存管理',
              name: 'isStockManage',  // 后台接受字段
              option: [
                {
                  name: '是',
                  value: '是'
                },
                {
                  name: '否',
                  value: '否'
                }
              ]
            },
            {
              label: '工厂',
              md: 12,
              disabled: disabled,
              type: 'input',
              placeholder: '工厂',
              name: 'factoryName'  // 后台接受字段
            },
            {
              label: '别名代码',
              md: 12,
              type: 'input',
              disabled: disabled,
              placeholder: '别名代码',
              name: 'warehouseAlias'  // 后台接受字段
            },
            {
              label: '区域模块',
              md: 12,
              type: 'input',
              disabled: disabled,
              placeholder: '区域模块',
              name: 'areaModel'  // 后台接受字段
            },
            {
              label: '批次ID',
              md: 12,
              type: 'input',
              disabled: disabled,
              placeholder: '批次ID',
              name: 'batchId'  // 后台接受字段
            },
            {
              label: '出库单解密',
              md: 12,
              type: 'input',
              disabled: disabled,
              placeholder: '出库单解密',
              name: 'isOdoDecrypt'  // 后台接受字段
            },

            {
              label: '备注',
              type: 'textarea',
              placeholder: '备注',
              disabled: disabled,
              labelCol: {
                xs: { span: 24 },
                sm: { span: 3 }
              },
              name: 'remarks'  // 后台接受字段
              // check: { rules: [{ required: true, message: '备注' }] },
            }
          ]
        }
        this.$refs.formAdd.edit(record, config)
        this.$refs.formAdd.disableSubmit = disableSubmit
      }
    }

  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>